import os
from openai import OpenAI

# 初始化OpenAI客户端
client = OpenAI(
    base_url="https://ark.cn-beijing.volces.com/api/v3/bots",
    api_key="cdc8987f-6ca0-4941-936f-1388ac326591"
)

# 定义问题文件路径
question_file_path = r"C:\Users\luowenjie\Desktop\客服热线\提示语\content.txt"


# 从文件读取问题内容
def read_question_from_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            # 读取文件全部内容，并去除首尾空白字符
            question = file.read().strip()
            # 如果文件内容为空，使用默认问题
            if not question:
                print("警告：问题文件为空，将使用默认问题")
                return "常见的十字花科植物有哪些？"
            return question
    except FileNotFoundError:
        print(f"警告：文件 {file_path} 未找到，将使用默认问题")
        return "常见的十字花科植物有哪些？"
    except Exception as e:
        print(f"警告：读取文件时出错 - {str(e)}，将使用默认问题")
        return "常见的十字花科植物有哪些？"


# 读取问题
user_question = read_question_from_file(question_file_path)
print(f"从文件读取的问题：{user_question}\n")

# 存储所有响应结果用于对比
all_responses = []

# 循环10次请求
for i in range(10):
    print(f"\n----- 第 {i + 1} 次请求 (streaming) -----")
    try:
        stream = client.chat.completions.create(
            model="bot-20251022163328-557c5",
            messages=[
                {"role": "user", "content": user_question},
            ],
            stream=True
        )

        print("响应内容:", end="")
        response_content = ""
        references = []
        for chunk in stream:
            if hasattr(chunk, "references"):
                references.extend(chunk.references)
            if not chunk.choices:
                continue
            if chunk.choices[0].delta.content:
                print(chunk.choices[0].delta.content, end="")
                response_content += chunk.choices[0].delta.content
        print()  # 换行

        # 存储结果
        all_responses.append({
            "iteration": i + 1,
            "content": response_content,
            "references": references
        })

    except Exception as e:
        print(f"请求出错: {str(e)}")
        all_responses.append({
            "iteration": i + 1,
            "error": str(e)
        })

# 打印对比结果
print("\n===== 多次请求结果对比 =====")
for idx, response in enumerate(all_responses, 1):
    print(f"\n--- 结果 {idx} ---")
    if "error" in response:
        print(f"错误: {response['error']}")
    else:
        print("响应内容:")
        print(response["content"])
        if response["references"]:
            print("\n参考资料:")
            for ref in response["references"]:
                print(ref)

